package org.example.excel;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.poi.ss.usermodel.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ExportExcelExample {
    public static void main(String[] args) throws IOException {
        // 创建数据列表
        List<User> userList = new ArrayList<User>();
        userList.add(new User("张三", "123456", "男", "北京市朝阳区"));
        userList.add(new User("李四", "abcdef", "女", "上海市浦东新区"));

        // 设置导出参数
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("Sheet1"); // 设置工作表名称
        exportParams.setType(ExcelType.XSSF); // 设置Excel类型为xlsx

        // 导出Excel
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, User.class, userList);

        //创建黄色背景样式
        CellStyle yellowBackground = workbook.createCellStyle();
        yellowBackground.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        yellowBackground.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 将两个样式合并到一个新的样式中
        CellStyle combinedStyle = workbook.createCellStyle();
        combinedStyle.cloneStyleFrom(yellowBackground);
        //集合居中样式
        combinedStyle.setAlignment(HorizontalAlignment.CENTER);

        // 设置第一行背景颜色为黄色，单元格字体居中
        Sheet sheet = workbook.getSheetAt(0);
        Row row = sheet.getRow(0);
        for (int i = 0; i < row.getLastCellNum(); i++) {
            // 应用新的样式到单元格，把第一行的背景颜色设置为黄色，并且内容设置居中
            row.getCell(i).setCellStyle(combinedStyle);
        }

        // 自适应列宽和行高
        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
            Row currentRow = sheet.getRow(i);
            if (currentRow != null) {
                currentRow.setHeight((short) -1); // 自动调整行高
                for (int j = 0; j < currentRow.getPhysicalNumberOfCells(); j++) {
                    Cell cell = currentRow.getCell(j);
                    if (cell != null) {
                        int columnWidth = sheet.getColumnWidth(j);
                        int contentLength = cell.toString().getBytes().length;
                        columnWidth = Math.max(columnWidth, contentLength * 256);
                        sheet.setColumnWidth(j, columnWidth);
                    }
                }
            }
        }

        // 保存到文件
        try {
            FileOutputStream fileOut = new FileOutputStream("D:/用户信息.xls");
            workbook.write(fileOut);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 关闭工作簿
        workbook.close();
    }
}
